﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuxuryResort.WebSite.LRMPDataService;

namespace LuxuryResort.WebSite.Members
{
    public partial class FoodBooking : Page
    {
        private readonly RoomServiceClient _svc = new RoomServiceClient();

        private Guid UserID
        {
            get
            {
                if (ViewState["UserID"] == null && HttpContext.Current.User != null)
                {
                    string userName = HttpContext.Current.User.Identity.Name;
                    MembershipUser membershipUser = Membership.GetUser(userName);
                    if (membershipUser != null)
                    {
                        object userId = membershipUser.ProviderUserKey;
                        ViewState["UserID"] = userId;
                    }
                }
                return (Guid) ViewState["UserID"];
            }
        }

        private Guid ResortId
        {
            get { return new Guid(ConfigurationManager.AppSettings["ResortId"]); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    FoodBeverage[] fbs = _svc.GetAllFood(UserID, ResortId);
                    lvFood.DataSource = fbs;
                    lvFood.DataBind();
                }
                catch (Exception ex)
                {
                    Response.Redirect("~/AccessDenied.aspx");
                }
            }
        }

        protected void btnBookFood_Click(object sender, EventArgs e)
        {
            IEnumerable<ListViewDataItem> selectedItems =
                lvFood.Items.Where(item => !string.IsNullOrEmpty(((TextBox) item.FindControl("txtQuantity")).Text));

            _svc.OrderFood((from ListViewItem item in selectedItems.ToList()
                let hidFid = ((HiddenField) item.FindControl("hidFid")).Value
                let quantity = ((TextBox) item.FindControl("txtQuantity")).Text
                let price = ((Label) item.FindControl("lblPrice")).Text
                select new FoodOrder
                {
                    CreatedAt = DateTime.Now,
                    CreatedBy = new Guid("82806ECE-5EFE-43ED-85F0-681881061426"),
                    CustomerName = txtCustomerName.Text,
                    FID = new Guid(hidFid),
                    ID = Guid.NewGuid(),
                    PaymentDone = chkPaymentDone.Checked,
                    Quantity = Convert.ToInt32(quantity),
                    Total = Convert.ToInt32(quantity)*Convert.ToDecimal(price)
                }).ToArray(), UserID, ResortId);
        }
    }
}